package com.ht.realm;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.ht.po.SysPermission;
import com.ht.po.SysUser;
import com.ht.service.ISysUserService;

/**
 * 
 * 自定义realm
 * @author Administrator
 *
 */
public class CustomRealm extends AuthorizingRealm {

	@Autowired
	private ISysUserService sysUserService;
	
	// 身份认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		// 得到用户名
		String usercode = (String) token.getPrincipal();
	
		SysUser user = sysUserService.getUserByuserCode(usercode);
		
		if(user == null) {
			return null;
		}
		
		// 查詢菜單
		List<SysPermission> menu = sysUserService.listMenu(user.getId());
		
		user.setMenu(menu);
		
		SimpleAuthenticationInfo sim = new SimpleAuthenticationInfo(user, user.getPassword(), "customRealm");
		
		return sim;
	}
	
	// 身份授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SysUser user = (SysUser) principals.getPrimaryPrincipal();
		
		// 查询用户权限
		List<SysPermission> listPermission = sysUserService.listPermission(user.getId());
		
		List<String> permission = new ArrayList<String>();
		
		for(SysPermission permissionPo : listPermission) {
			// 获取权限标识
			String permissionName = permissionPo.getPercode();
			permission.add(permissionName);
		}
		
		SimpleAuthorizationInfo sim = new SimpleAuthorizationInfo();
		sim.addStringPermissions(permission);
		
		return sim;
	}
}
